#include "Application.hpp"
#include <string>



Application::Application(int argc, char *argv[])
  : aer::Application()
{  
  m_Window = createWindow( aer::Window::sDisplay_GL33_800x600, "Deferred test");
  m_Window->setVerticalSync( true );
  
  
  // Binary directory
  std::string binPath(argv[0]);
  size_t n = binPath.find_last_of('/'); binPath.resize(n+1);
  
  // Shader directory
  std::string shaderPath(binPath);
  shaderPath += "../tests/deferred/shaders/"; // xxx (hardcoded)
  
  //aer::Path shaderPath(argv[0]);
  //shaderPath.changeDirectory( "../tests/deferred/shaders/" );
  
  glswInit();
  glswSetPath( shaderPath.c_str(), ".glsl");
  glswAddDirectiveToken("*", "#version 330 core");
}

Application::~Application()
{
  glswShutdown();
}


void Application::init()
{
  m_data.init( &m_scene );
  m_scene.init();
  m_renderer.init(m_data);
  
  CHECKGLERROR();
}


// -----------------------------------------------------------


void Application::updateFrame()
{
  // ============
  // == Events ==
  // ============
  if (aer::EventHandler::IsKeyPressed( sf::Keyboard::Escape )) quit();
  
  if (aer::EventHandler::IsKeyPressed( sf::Keyboard::F )) {
    printf("fps : %u\n", m_timer.getFPS());
  }
  
  if (aer::EventHandler::IsKeyDown( sf::Keyboard::W )) {
    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
  } else {
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);
  }
  //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
  
  if (aer::EventHandler::HasResized())
  {
    const aer::Display &display = m_Window->getDisplay();
    
    m_data.resize( display.width, display.height);
    m_renderer.resize( display.width, display.height);
    
    glViewport( 0, 0, display.width, display.height);//
  }
  
  // ============
  // == Update ==
  // ============
  m_data.update();
  m_scene.update();
  m_renderer.update(m_data);
  
  
  CHECKGLERROR();
}


void Application::drawFrame()
{
  m_renderer.run( m_data );  
  
  CHECKGLERROR();
}
